﻿using Microsoft.AspNetCore.SignalR;

namespace WebApi.Filters;

/// <summary>
/// 自定义Hub过滤器
/// </summary>
public class CustomHubFilter : IHubFilter
{
    /// <summary>
    /// 自定义Hub过滤器触发方法
    /// </summary>
    /// <param name="invocationContext"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async ValueTask<object?> InvokeMethodAsync(
        HubInvocationContext invocationContext,
        Func<HubInvocationContext, ValueTask<object?>> next)
    {
        // Do something before the method is invoked
        // For example, log the method name
        Console.WriteLine($"Invoking method: {invocationContext.HubMethodName}");
        try
        {
            // Call the next delegate/middleware in the pipeline
            var result = await next(invocationContext);
            // Do something after the method is invoked
            // For example, log the result
            Console.WriteLine($"Method {invocationContext.HubMethodName} returned: {result}");
            return result;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{invocationContext.HubMethodName} 抛异常了：{ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// 自定义Hub过滤器连接方法 可选方法
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> next)
    {
        // Do something before the connection is established
        next(context);
        // Do something after the connection is established
        Console.WriteLine($"Client connected: {context.Context.ConnectionId}");
        // You can also access the connection context and perform actions like adding to groups
        // await context.Groups.AddToGroupAsync(context.Context.ConnectionId, "SomeGroup");
        // await context.Groups.AddToGroupAsync(context.Context.ConnectionId, "SignalR User");
        return Task.CompletedTask;
    }

    /// <summary>
    /// 自定义Hub过滤器断开连接方法 可选方法
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <param name="exception"></param>
    /// <returns></returns>
    public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func<HubLifetimeContext, Exception?, Task> next)
    {
        // Do something before the connection is disconnected
        next(context, exception);
        // Do something after the connection is disconnected
        Console.WriteLine($"Client disconnected: {context.Context.ConnectionId}");
        return Task.CompletedTask;
    }


}
